package com.yuan.j2ee.thread.learn01;

import java.util.concurrent.Semaphore;

public class T11_semaphore {
    public static void main(String[] args) {
        char[] aI = "123456789".toCharArray();
        char[] aC = "ABCDEFGHI".toCharArray();
       // 同步关键类，构造方法传入的数字是多少，则同一个时刻，只运行多少个进程同时运行制定代码
        Semaphore semaphore1 = new Semaphore(1, false);
        Semaphore semaphore2 = new Semaphore(0, false);

        new Thread(() -> {
           for (char c : aI) {
               try {
                   // //获取许可
                   semaphore1.acquire();
               } catch (Exception e) {
                   e.printStackTrace();
               }
               System.out.print(c);
               // 释放
               semaphore2.release();
           }
        }, "t1").start();

        new Thread(() -> {
            for (char c : aC) {
                try {
                    semaphore2.acquire();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.print(c);
                semaphore1.release();
            }
        }, "t2").start();
    }
}
